using System;
using System.Linq;
using System.Threading.Tasks;
using DnsClient;

namespace Comteck.ConsulCluster.Extensions {
  /// <summary>
  /// 
  /// </summary>
  public static class DnsQueryExtensions {
    /// <summary>
    /// 根据服务名称去Consul获取对应的地址列表，支持负载均衡
    /// </summary>
    /// <param name="dns">IDnsQuery</param>
    /// <param name="conulName">Consul的服务名称，默认为 service.consul</param>
    /// <param name="serviceName">需要请求的服务名称</param>
    /// <param name="apiName">api服务名称</param>
    /// <returns></returns>
    public static async Task<string> GetUrlAsync(this IDnsQuery dns, string conulName, string serviceName,
      string apiName = null) {
      // 获取service的列表
      var serviceHostList = await dns.ResolveServiceAsync(conulName, serviceName);

      if (serviceHostList == null || serviceHostList.Count() == 0) {
        throw new Exception("serviceName address not exists");
      }

      // combine url
      var service = serviceHostList.First();

      var host = string.Empty;
      if (service.AddressList == null || service.AddressList.Length == 0) {
        host = service.HostName;
      } else {
        host = service.AddressList.FirstOrDefault().ToString();
      }

      var builder = new UriBuilder("http", host, service.Port, apiName);
      return builder.ToString();
    }

    ///// <summary>
    ///// 
    ///// </summary>
    ///// <param name="consulClient"></param>
    ///// <returns></returns>
    //public static async Task<string> GetUrlAsync(IConsulClient consulClient) {
    //  // 直接从consul获取指定服务名称的节点，没有实现负载均衡
    //  var consulResult = await consulClient.Catalog.Service("");

    //  //var healthResult = await _consulClient.Health.Service(_options.Value.ServiceName, tag: null, passingOnly: true);

    //  return "";
    //}

  }
}
